package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHSWUtil
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

public class api_SendA00014 implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(api_SendA00014.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String getMethod = request.getMethod();
        log.debug("api_SendA00014 getMethod:" + getMethod);
        String outData = "200";
        if (!getMethod.equals("GET")) {
            outData = "HTTP请求调用类型错误，接口调用失败：" + getMethod;
            log.error(outData);
            return outData;
        }

        //获取所有参数名
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String parameterName = (String) ep.nextElement();
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        // 获取嵌入传递的参数
        String sms_guid = request.getParameter("sms_guid");
        String bch_guid = request.getParameter("bch_guid");
        if (KHUtil.isNull(sms_guid)) {
            outData = "api_SendA00014 HTTP请求调用错误，任务ID为空：" + sms_guid;
            log.error(outData);
            return outData;
        }
        if (KHUtil.isNull(bch_guid)) {
            outData = "api_SendA00014 HTTP请求调用错误，批次ID为空：" + bch_guid;
            log.error(outData);
            return outData;
        }

        //获取批次是否已经发送
        String checkSQL = '''Select r1.documentout_guid,r1.Documentpath,r1.documentto,r1.expectedstartdate
                              From Documentout_Ucis_Batch R1
                              Left Join Documentout_Ucis_Batch_Result R2
                                On R1.Documentout_Guid = R2.Documentout_Guid
                             Where R2.Documentout_Guid Is Not Null
                                   And R1.Sms_Guid = \'''' + sms_guid + '''\'
                                   And R1.Batch_Id = \'''' + bch_guid + '''\'''';
        List checkSQLList = eliteBean.chaxun_sql(checkSQL, "dataSource");
        if (checkSQLList.size() > 0) {
            outData = "api_SendA00014 HTTP请求调用错误，批次ID已经有过发送：" + bch_guid;
            log.error(outData);
            return outData;
        }

        try {
            // 调用处理信息
            int SMSCount = 0;//累计数
            String message = "";
            String msg = "";
            String outdata = "";
            String content = sms_guid;
            String documentout_guid = "";
            String documentpath = "";
            String documentto = "";
            String expectedstartdate = "";//短信入参

            String busdept = "";//短信发送类型
            String ext1 = "";//短信计划批次名称

            log.debug("api_SendA00014 待处理名单线程Guid：" + content);

            // 获取短信批次的ID
            sms_guid = content;
            log.debug("api_SendA00014 获取短信批次的ID-sms_guid：" + sms_guid);

            //查询当前催缴批次 在系统内是否有待发送的短信
            String sendSQL = '''Select r1.documentout_guid,r1.Documentpath,r1.documentto,r1.expectedstartdate
                                  From Documentout_Ucis_Batch R1
                                  Left Join Documentout_Ucis_Batch_Result R2
                                    On R1.Documentout_Guid = R2.Documentout_Guid
                                 Where R2.Documentout_Guid Is Null
                                   And R1.Sms_Guid = \'''' + sms_guid + '''\'
                                   And R1.Batch_Id = \'''' + bch_guid + '''\'''';
            List selectdocucisList = eliteBean.chaxun_sql(sendSQL, "dataSource");
            int docuciscount = selectdocucisList.size();
            log.debug("api_SendA00014 待发送催缴短信数量docuciscount：" + docuciscount);

            //判断如短信数量大于0则执行
            if (docuciscount > 0) {
                //监控更新短信发送开始时间
                eliteBean.update("Update Ucis_Sms_Monitoring Set Sendsms_Starttime = Getdate() Where Sms_Guid = '" + sms_guid + "' And Sendsms_Starttime Is Null", "dataSource");
                //获取短信部门
                List selectbusdeptresult = eliteBean.chaxun_sql("select top 1 b.sms_type as busdept,a.SMS_NAME as ext1 from Ucis_Smssendplan a left join ucis_deptcode b on a.DEPTCODE=b.DEPTCODE  where a.REC_GUID='" + sms_guid + "'", "dataSource");
                if (selectbusdeptresult.size() > 0) {
                    busdept = selectbusdeptresult.get(0).get("busdept");
                    ext1 = selectbusdeptresult.get(0).get("ext1");
                }
                log.debug("api_SendA00014 发送短信类型busdept：" + busdept);

                //循环执行发送
                for (int j = 0; j < docuciscount; j++) {
                    Map selectdocucisMap = selectdocucisList.get(j);
                    documentout_guid = selectdocucisMap.get("documentout_guid");
                    documentpath = selectdocucisMap.get("documentpath");
                    documentto = selectdocucisMap.get("documentto");

                    String userMsgId = "BSMS_" + KHUtil.getRandomString(15);
                    outdata = sendsms(eliteBean, documentout_guid, documentto, documentpath, "交费通知", busdept, userMsgId, "", ext1);
                    log.debug("api_SendA00014 outdata：" + outdata);

                    //解析返回信息
                    org.json.JSONObject jsonObject = new org.json.JSONObject(outdata);
                    String statusCode = KHUtil.GetJV(jsonObject, "statusCode");
                    String resultMsg = KHUtil.GetJV(jsonObject, "resultMsg");
                    String resultCode = KHUtil.GetJV(jsonObject, "resultCode");
                    log.debug("api_SendA00014 statusCode：" + statusCode);
                    //成功提交
                    if (statusCode == "0") {
                        SMSCount++;
                        String updateDocumentoutSQL = '''Insert Into Documentout_Ucis_Batch_Result
                                                          (Documentout_Guid, Resultcode, Usermsgid, Send_Code, Send_Msg, Send_Time)
                                                        Values
                                                          (\'''' + documentout_guid + '''\', \'''' + resultCode + '''\', \'''' + userMsgId + '''\', \'''' + statusCode + '''\', \'''' + resultMsg + '''\', Getdate())''';

                        int updateDocumentouFlag = eliteBean.update(updateDocumentoutSQL, "dataSource");
                        log.debug("api_SendA00014 写入短信平台接口成功-短信平台回写Documentout_Ucis_Batch_Result表SQL执行结果:" + updateDocumentouFlag);
                        //提交有返回，但是属于非成功的
                    } else {

                        String updateDocumentoutSQL = '''Insert Into Documentout_Ucis_Batch_Result
                                                          (Documentout_Guid, Resultcode, Usermsgid, Send_Code, Send_Msg, Send_Time)
                                                        Values
                                                          (\'''' + documentout_guid + '''\', \'''' + resultCode + '''\', \'''' + userMsgId + '''\', \'''' + statusCode + '''\', \'''' + resultMsg + '''\', Getdate())''';

                        int updateDocumentouFlag = eliteBean.update(updateDocumentoutSQL, "dataSource");
                        log.debug("api_SendA00014 写入短信平台接口失败-短信平台回写Documentout_Ucis_Batch_Result表SQL执行结果:" + updateDocumentouFlag);
                    }
                }
                msg = "批次：" + sms_guid + " ,符合条件短信有" + docuciscount + "条数据，成功插入" + SMSCount + "条！";
                log.debug("api_SendA00014 当前需要发送短信的数据处理结果:" + msg);
            } else {
                log.debug("api_SendA00014 当前批次：" + sms_guid + " ,待发送催缴短信数量为0！");
            }

        } catch (Exception e) {
            outData = "api_SendA00014 对接api_SendA00014处理完成异常" + e.getMessage();
            log.error(outData);

        }

        log.debug("api_SendA00014 对接api_SendA00014处理完成-结果:" + outData);

        return outData;
    }


    //短信发送接口
    public static String sendsms(EliteBean eliteBean, String Documentout_Guid, String mobile, String content, String businessType, String loginName, String userMsgId, String extInfo, String batchName) {

        JSONObject sendResultJson = KHSWUtil.sendSWSms(eliteBean, Documentout_Guid, mobile, content, loginName, businessType, userMsgId, extInfo, batchName);

        String statusCode = sendResultJson.has("code") ? sendResultJson.getString("code") : "-1";
        String resultMsg = sendResultJson.has("msg") ? sendResultJson.getString("msg") : "";
        String resultCode = sendResultJson.has("msgId") ? sendResultJson.getString("msgId") : "";

        org.json.JSONObject resultJson = new org.json.JSONObject();
        resultJson.put("statusCode", statusCode);
        resultJson.put("resultMsg", resultMsg);
        resultJson.put("resultCode", resultCode);

        return resultJson.toString();
    }
}
